package com.tj.feige.app;

import android.app.Activity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FeiGeBaseUI extends Activity implements View.OnKeyListener {
    private String a(Uri uri) {
        Cursor cursor = this.managedQuery(uri, new String[]{"_data"}, (String)null, (String[])null, (String)null);
        String file_path;
        String uri_path = uri.toString();
        if(cursor==null) return "";
        try {
            int data = cursor.getColumnIndexOrThrow("_data");
            cursor.moveToFirst();
            file_path = cursor.getString(data);
            Log.e("FeiGe","接收到旧版风格的URI，内容为：" + uri_path);
            if(file_path==null){
                // content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3AAndroid%2Fdata%2Forg.thunderdog.challegram%2Ffiles%2Fdocuments%2FCharles_Petzold_Pet_z_lib_org.epub
                //Toast.makeText(this,"警告：当前无法获取到文件路径，请勿继续分享",Toast.LENGTH_LONG).show();
                // %2F 是 / 的URI编码
                file_path = copyFileToCache(uri,"%2F");
            }
        }catch (IllegalArgumentException e){
            // 修复无法处理 FileProvider的 content:// URI的问题
            // 参考 https://github.com/getodk/collect/pull/4265/commits/425fe52fbfe60764be9eb4b499414a00a9ea4cf6
            Log.e("FeiGe","接收到新版风格的URI，内容为：" + uri_path);
            file_path = copyFileToCache(uri,"/");
        }
        Log.e("FeiGe","文件位置为" + file_path);
        return file_path;
    }

    private String copyFileToCache(Uri uri,String delimiter){
        String uri_path = uri.toString();
        String file_name = uri_path.substring(uri_path.lastIndexOf(delimiter) + delimiter.length());
        // 无论哪种来源都可以尝试调用URI解码，不再区分分隔符的差异
        file_name = Uri.decode(file_name);
        File tmp_file = new File(this.getCacheDir(),file_name);
        cleanCache();
        logCache(file_name);
        try(InputStream is = this.getContentResolver().openInputStream(uri);
            OutputStream os = new FileOutputStream(tmp_file)){
            byte[] buffer = new byte[1024 * 1024 * 4];
            int len = 0;
            while((len=is.read(buffer)) > 0){
                os.write(buffer,0,len);
            }
        }catch (Exception e0){
            e0.printStackTrace();
            Toast.makeText(this,e0.toString(),Toast.LENGTH_LONG).show();
            return null;
        }
        // 退出程序时尝试清除缓存的文件
        tmp_file.deleteOnExit();
        return tmp_file.getAbsolutePath();
    }

    private void logCache(String fileName){
        SharedPreferences sp = getSharedPreferences("cache_file",MODE_PRIVATE);
        sp.edit().putString("cache_file",fileName).apply();
    }
    private void cleanCache(){
        SharedPreferences sp = getSharedPreferences("cache_file",MODE_PRIVATE);
        String file_name = sp.getString("cache_file", "null");
        File file = new File(getCacheDir(), file_name);
        if(file.exists() && file.isFile()){
            file.delete();
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        return false;
    }
}
